package cn.tedu.car.backend.user.service.impl;

import cn.tedu.car.backend.base.exception.ServiceException;
import cn.tedu.car.backend.base.response.Constants;
import cn.tedu.car.backend.base.response.StatusCode;
import cn.tedu.car.backend.user.enums.UserStatus;
import cn.tedu.car.backend.user.mapper.SystemuserMapper;
import cn.tedu.car.backend.user.pojo.dto.LoginDTO;
import cn.tedu.car.backend.user.pojo.dto.UserQueryParam;
import cn.tedu.car.backend.user.pojo.dto.UserSaveParam;
import cn.tedu.car.backend.user.pojo.po.SystemuserPO;
import cn.tedu.car.backend.user.pojo.vo.LoginVO;
import cn.tedu.car.backend.user.pojo.vo.UserVO;
import cn.tedu.car.backend.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SystemuserMapper systemuserMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 根据用户名查询用户
        LoginVO loginVO = systemuserMapper.selectLoginSystemuser(loginDTO.getUsername());

        if(loginVO==null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if(!loginVO.getPassword().equals(loginDTO.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }

        return loginVO;
    }

    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        // 判断是新增还是修改，id为null，则新增
        if (userSaveParam.getId() == null) {
            SystemuserPO systemuserPO = new SystemuserPO();
            BeanUtils.copyProperties(userSaveParam, systemuserPO);
            systemuserPO.setCtime(new Date());
            systemuserPO.setPassword(Constants.DEFAULT_PASSWORD);
            systemuserMapper.insertSystemuser(systemuserPO);
        } else {
            SystemuserPO systemuserPO = new SystemuserPO();
            BeanUtils.copyProperties(userSaveParam, systemuserPO);
            systemuserMapper.updateSystemuser(systemuserPO);
        }
    }

    @Override
    public List<UserVO> listUser(UserQueryParam userQueryParam) {
        return systemuserMapper.listSystemuser(userQueryParam);
    }

    @Override
    public void changUserStatus(Long userId, UserStatus oldUserStatus, UserStatus newerUserStatus) {
        systemuserMapper.updateSystemuserStatus(userId, oldUserStatus, newerUserStatus);
    }
}
